#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdarg.h>
#include "common.h"
#include "log.h"

#define LOG_DIR  "./log"

void init_log(void){
    char mkdir[64] = {0};
    if(access(LOG_DIR,F_OK) != 0){
        sprintf(mkdir,"mkdir %s",LOG_DIR);
        system(mkdir);
    }
}

void get_log_file_path(char* path){
    char date[32] = {0};
    get_date(date);
    sprintf(path,"%s/%s",LOG_DIR,date);
}

int write_log(char* fmt,...){
    char *msg;
    va_list arg;
    int ret;

    va_start(arg, fmt);
    ret = vsnprintf(NULL, 0, fmt, arg);
    va_end(arg);
    if (ret < 0 || (msg = malloc(ret + 1)) == NULL) return;
    va_start(arg, fmt);
    ret = vsnprintf(msg, ret + 1, fmt, arg);
    va_end(arg);

    FILE* fp;
    char* p_log = NULL;
    if((p_log = malloc(strlen(msg)+256)) == NULL) {
        free(msg);
        return;
    }
    get_log_file_path(p_log);
    fp = fopen(p_log,"a+");
    if(fp){        
        get_exact_time(p_log);
        sprintf(p_log+strlen(p_log),":------------------------------\n\n%s\n\n",msg);
        strcat(p_log,"--------------------------------------------------\n\n\n\n\n\n");
        fwrite(p_log,strlen(p_log),1,fp);
        fclose(fp);
    }
    free(p_log);
    free(msg);
    
}